import { _decorator, Component, Node, Vec3, math } from 'cc';
import { PathMove } from './PathMove'; // 确保根据实际路径导入
import { PathEvent } from './PathEvent';

const { ccclass, property } = _decorator;

@ccclass('PathEvent_LookNextPoint')
export class PathEvent_LookNextPoint extends PathEvent {

    @property
    public is3D: boolean = false; // 是否使用3D模式

    public override addEvent(): void {
        if (this.pathMove) {

            this.pathMove.onNextPointChanged = (next)=>{
                var dis = Vec3.distance(next,this.node.worldPosition);
                if(dis > 0.01){
                    this.lookAtNextPoint(this.pathMove.node.worldPosition, next);
                }
            };
        }
    }
    
    

    /**
     * 在路径点开始时，让目标物体朝向下一个点
     * @param index - 当前路径点索引
     * @param allPathPoints - 所有路径点
     */
    private lookAtNextPoint(from:Vec3,to:Vec3) {

        let direction = to.clone().subtract(from);
        direction = direction.normalize();
        
        if (this.is3D) {
            this.target.forward = direction.negative();
        } else {
            this.target.setRotationFromEuler(0, -math.toDegree(Math.atan2(direction.z, direction.x)), 0);
        }
    }
}
